package com.ph.shopping.facade.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.mapper.PhProductClassifyExtendMapper;
import com.ph.shopping.facade.mapper.PhProductImageMapper;
import com.ph.shopping.facade.mapper.PhProductMapper;
import com.ph.shopping.facade.mapper.PhProductPropertyValMapper;
import com.ph.shopping.facade.product.entity.PhProduct;
import com.ph.shopping.facade.product.entity.PhProductImage;
import com.ph.shopping.facade.product.entity.PhProductPropertyVal;
import com.ph.shopping.facade.product.service.IProductService;
import com.ph.shopping.facade.product.vo.PhOrderProductVo;
import com.ph.shopping.facade.product.vo.PhProductClassifyExtendVo;
import com.ph.shopping.facade.product.vo.PhProductImageVo;
import com.ph.shopping.facade.product.vo.PhProductVo;
import com.ph.shopping.facade.supplier.entity.Supplier;
import com.ph.shopping.facade.supplier.service.ISupplierService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
/**
 * @项目：phshopping-service-product
 * @描述： 商品service实现类
 * @作者： hewl
 * @创建时间：2017年3月6日 上午11:15
 * @Copyright by hewl
 * @version 1.0.0
 */
@Component
@Service(version="1.0.0")
public class ProductServiceImpl extends BaseService implements IProductService {
	
	private static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
	
	@Autowired
	private PhProductMapper phProductMapper;

	@Autowired
	private PhProductImageMapper phProductImageMapper;

	@Autowired
	private PhProductPropertyValMapper phProductPropertyValMapper;

	@Reference(version = "1.0.0")
	ISupplierService supplierService;
	//引用商品类型商城扩展的mapper
	@Autowired
	private PhProductClassifyExtendMapper phProductClassifyExtendMapper;
	/**
	 * 商品添加方法
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result addProduct(PhProduct phProduct, List<PhProductImage> imageList, List<PhProductPropertyVal> ppvList) throws Exception {
//		Result result = new Result();
			int msg;
			logger.info("调用商品添加接口实现类开始");
			phProduct.setReferencePrice(MoneyTransUtil.transMulti(phProduct.getReferencePrice() == null ? new BigDecimal("0") : phProduct.getReferencePrice()));//市场参考价
			phProduct.setRetailPrice(MoneyTransUtil.transMulti(phProduct.getRetailPrice() == null ? new BigDecimal("0") : phProduct.getRetailPrice()));//零售价
			phProduct.setPurchasePrice(MoneyTransUtil.transMulti(phProduct.getPurchasePrice() == null ? new BigDecimal("0") : phProduct.getPurchasePrice()));//进货价
			phProduct.setSettlementPrice(MoneyTransUtil.transMulti(phProduct.getSettlementPrice() == null ? new BigDecimal("0") : phProduct.getSettlementPrice()));//结算价
			//phProduct.setPromotionPrice(MoneyTransUtil.transMulti(phProduct.getPromotionPrice() == null ? new BigDecimal("0") : phProduct.getPromotionPrice()));//促销价
			phProduct.setFreight(MoneyTransUtil.transMulti(phProduct.getFreight() == null ? new BigDecimal("0") : phProduct.getFreight()));//物流费
			// 获取商品返回id
		    msg=this.phProductMapper.insertUseGeneratedKeys(phProduct);
			// 将商品id赋值给图片的ProductId
			for (PhProductImage image : imageList) {
				image.setProductId(phProduct.getId());
			}
			 msg= this.phProductImageMapper.insertList(imageList);
			 if(ppvList.size()>0){
				for (PhProductPropertyVal val : ppvList) {
					val.setProductId(phProduct.getId());
				}
				 msg=this.phProductPropertyValMapper.insertList(ppvList);
			 }
			 if(msg==1){
				 return getResult(ResultEnum.SUCCESS);
				}else{
				return getResult(ResultEnum.ADD_PRODUCT_PROPERTY_EXCEPTION);
		}
	}
	
	
	
	
	
	@Transactional(rollbackFor = Exception.class)
	public Result updateProduct(PhProduct phProduct, List<PhProductImage> imageList, 
			List<PhProductPropertyVal> pvList) throws Exception{
		logger.debug("修改商品开始");
		logger.debug("phProduct: " + new ObjectMapper().writeValueAsString(phProduct));
		logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));
		logger.debug("pvList: " + new ObjectMapper().writeValueAsString(pvList));
		//金额转换
		phProduct.setReferencePrice(MoneyTransUtil.transMulti(phProduct.getReferencePrice() == null ? new BigDecimal("0")  : phProduct.getReferencePrice()));//市场参考价
		phProduct.setRetailPrice(MoneyTransUtil.transMulti(phProduct.getRetailPrice() == null ? new BigDecimal("0") : phProduct.getRetailPrice()));//零售价
		phProduct.setPurchasePrice(MoneyTransUtil.transMulti(phProduct.getPurchasePrice() == null ? new BigDecimal("0") : phProduct.getPurchasePrice()));//进货价
		phProduct.setSettlementPrice(MoneyTransUtil.transMulti(phProduct.getSettlementPrice() == null ? new BigDecimal("0") : phProduct.getSettlementPrice()));//结算价
		//phProduct.setPromotionPrice(MoneyTransUtil.transMulti(phProduct.getPromotionPrice() == null ? new BigDecimal("0") : phProduct.getPromotionPrice()));//促销价
		phProduct.setFreight(MoneyTransUtil.transMulti(phProduct.getFreight() == null ? new BigDecimal("0") : phProduct.getFreight()));//物流费
		
		//设置删除已有的图片条件
		Example example = new Example(PhProductImage.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("productId", phProduct.getId());
		
		// 设置删除已有的属性值条件
		Example propertyExample = new Example(PhProductPropertyVal.class);
		Criteria criteriPropertyExample = propertyExample.createCriteria();
		criteriPropertyExample.andEqualTo("productId", phProduct.getId());
	
		//修改商品
		phProductMapper.updateByPrimaryKeySelective(phProduct);
		logger.debug("修改商品");
		//删除已有的图
		phProductImageMapper.deleteByExample(example);
		logger.debug("删除已有的图");
		
		if(imageList.size()>0){
			//新增当前图片
			phProductImageMapper.insertList(imageList);
			logger.debug("新增当前图片");
		}
		//删除已有的属性值
		phProductPropertyValMapper.deleteByExample(propertyExample);
		logger.debug("删除已有的属性值");
		
		if(pvList.size() > 0){
		//新增当前属性值
			phProductPropertyValMapper.insertList(pvList);
			logger.debug("新增当前属性值");
		}
		
		logger.debug("修改商品成功");
		logger.debug("phProduct: " + new ObjectMapper().writeValueAsString(phProduct));
		logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));
		logger.debug("pvList: " + new ObjectMapper().writeValueAsString(pvList));
		return getResult(ResultEnum.SUCCESS);
	}

		/**
		 * 商品查看单条/多条详情记录查询(不要使用分页查询)
		 * @author hewl
		 * @param PhProductVo
		 * @return List<PhProductVo>
		 */
		public	List<PhProductVo> getProductVoDetail(PhProductVo phProductVo) throws Exception{
			return phProductMapper.getPhProductVoDeliList(phProductVo);
		}
		
		/**
		 * 商品分页列表查询 
		 * @author hewl
 		 * @param PhProductVo
		 * @return Result
		 */
		public Result getProductVoPageList(PageBean pageBean,PhProductVo phProductVo) throws Exception{
			
			PhProductClassifyExtendVo extendsVo = new PhProductClassifyExtendVo();//首先查询二级和三级下面的数据
			if(StringUtils.isNotEmpty(String.valueOf(phProductVo.getProductClassifyId()))){
				extendsVo.setFjId(String.valueOf(phProductVo.getProductClassifyId()));
				List<PhProductClassifyExtendVo> extendsList = phProductClassifyExtendMapper.getPhProductClassifyExtendVoList(extendsVo);
				if(extendsList.size()>0){
					phProductVo.setProductClassifyId(0L);
					String classifyExtendId = "";
					for(PhProductClassifyExtendVo v : extendsList){
						for(String param:v.getZhid().split(",")){
							if(StringUtils.isNotEmpty(param)){
								if(classifyExtendId.indexOf(param)<0){
									classifyExtendId+=param+",";
								}
							}
						}
					}
					if(StringUtils.isNotEmpty(classifyExtendId))//数组转换成list
						phProductVo.setProductClassifyIdList(Arrays.asList(classifyExtendId.substring(0, classifyExtendId.lastIndexOf(",")).split(",")));
				}
			}
			PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
			List<PhProductVo> list = (Page<PhProductVo>)phProductMapper.getPhProductVoList(phProductVo);
			PageInfo<PhProductVo> pageInfo =new PageInfo<PhProductVo>(list);
			return new Result(ResultEnum.SELECT_PRODUCT_EXCEPTION.getCode(),"",pageInfo.getList(),pageInfo.getTotal());
		}
		
		/**
		 * 商品列表查询 
		 * @author hewl
 		 * @param PhProductVo
		 * @return List<PhProductVo>
		 */
		public List<PhProductVo> getProductVoList(PhProductVo phProductVo) throws Exception{
			return phProductMapper.getPhProductVoList(phProductVo);
		}
		
		/**
		 * 商品图片查询 
		 * @author hewl
 		 * @param phProductVo
		 * @return List<PhProductVo>
		 */
		public Map<String,Object> getProductVoImageList(PageBean pageBean,PhProductVo phProductVo) throws Exception{
			Map<String,Object> map = new HashMap<String,Object>();
			PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
			List<PhProductVo> list =  phProductMapper.getPhProductVoList(phProductVo);
			if(list.size()>0){
				for(PhProductVo v: list){
					PhProductImageVo imgVo = new PhProductImageVo();
					imgVo.setProductId(v.getId());
					v.setPhProductImageVoList(phProductImageMapper.getPhProductImageList(imgVo));
				}
			}
			PageInfo<PhProductVo> info = new PageInfo<PhProductVo>(list);
			map.put("data", info.getList());
			return map;
		}
		/**
		 * 单条商品列表查询 
		 * @author hewl
 		 * @param PhProductVo：id
		 * @return PhProductVo
		 */
		public PhProductVo getPhProductVo(PhProductVo phProductVo) throws Exception{
			List<PhProductVo> list = phProductMapper.getPhProductVoList(phProductVo);
			if(list.size()>0){
				phProductVo = list.get(0);
			}
			return phProductVo;
		}
		/**
		 * 逻辑删除商品
		 * @author hewl
		 * @param phProductVo:id
		 * @return Result
		 */
		@Transactional(rollbackFor=Exception.class)
		public Result deleteLogicPhProduct(PhProductVo phProductVo) throws Exception{
			Integer returnValue = phProductMapper.deleteLogicPhProduct(phProductVo);
			Result result=new Result();
			result.setCode("200");
			if(returnValue>0){
				result.setMessage("删除成功");
			}
			return result;
		}
		/**
		 * 审核商品
		 * @author hewl
		 * @param phProductVo:id-auditState
		 * @return Result
		 */
		@Transactional(rollbackFor=Exception.class)
		public Result auditPhProduct(PhProductVo phProductVo) throws Exception{
			Integer returnValue = phProductMapper.auditPhProduct(phProductVo);
			Result result=new Result();
			if(returnValue>0){
				result.setMessage("操作成功");
			}
			return result;
		}
		/**
		 * 商品上架、下架
		 * @author hewl
		 * @param phProductVo:id-saleNoSaleStatus
		 * @return Result
		 */
		@Transactional(rollbackFor=Exception.class)
		public Result onsalPhProduct(PhProductVo phProductVo) throws Exception{
			Integer returnValue = phProductMapper.onsalPhProduct(phProductVo);
			Result result=new Result();
			if(returnValue>0){
				result.setMessage("操作成功");
			}
			return result;
		}
	/**
	 * 通过商品id查询商品集合
	 * @param productIds
	 * @return
	 */
	@Override
	public Result getPhProductList(List<Long> productIds) {
		List<PhProductVo> list = phProductMapper.getPhProductList(productIds);
		return getResult(ResultEnum.SUCCESS,mergeProduct(list));
	}

	/**
	 * 扣除商品数量
	 * @param phProductVo
	 * @return
	 * @author zhengpeng
	 */
	@Transactional
	@Override
	public Result reduceStock(PhProductVo phProductVo) {
		logger.info("扣除商品数量入参：phProductVo={}",JSON.toJSONString(phProductVo));
		phProductVo.setUpdateTime(new Date());
		Result result = getResult(ResultEnum.SUCCESS,phProductMapper.reduceStock(phProductVo));
		logger.info("扣除商品数量出参：result={}",JSON.toJSONString(result));
		return result;
	}

	/**
	 * 供应商id进行分组
	 * @param list
	 * @return
	 * @author zhengpeng
	 */
	private List<PhOrderProductVo> mergeProduct(List<PhProductVo> list) {
		PhOrderProductVo phOrderProductVo;
		Map<Long,List<PhProductVo>> map = new HashMap<>();
		List<PhProductVo> group;
		PhProductVo item;
		List<PhOrderProductVo> phOrderProductVoList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			item = list.get(i);
			if (null == item.getSellerbAtchQuantity()) {
				//设置起批数量为1
				item.setSellerbAtchQuantity(1);
			}
			if (null == item.getMunicipalBatchQuantity()) {
				//设置起批数量为1
				item.setMunicipalBatchQuantity(1);
			}
			if (map.containsKey(item.getSupplierId())) {
				map.get(item.getSupplierId()).add(item);
			} else {
				group = new ArrayList<>();
				group.add(item);
				map.put(item.getSupplierId(),group);
			}
		}

		//循环map，通过供应商id查询供应商名称
		Long getSupplierId;
		PhProductVo vo;
		for (Map.Entry<Long, List<PhProductVo>> entry : map.entrySet()) {
			phOrderProductVo = new PhOrderProductVo();
			getSupplierId = entry.getKey();
			phOrderProductVo.setSupplierId(getSupplierId);
			//供应商名称
			phOrderProductVo.setSupplierName(getSupplierName(getSupplierId));
			phOrderProductVo.setPhProductVoList(entry.getValue());
			phOrderProductVoList.add(phOrderProductVo);
		}
		return phOrderProductVoList;
	}

	/**
	 * 查询供应商名称
	 * @param id
	 * @return
	 * @author zhengpeng
	 */
	private String getSupplierName(Long id) {
		String supplierName = "";
		try {
			Supplier supplier = new Supplier();
			supplier.setId(id);
			logger.info("通过供应商id查询供应商信息接口入参: supplier={}", JSON.toJSONString(supplier));
			Supplier result = supplierService.getSupplierById(supplier);
			logger.info("通过供应商id查询供应商信息接口返回值: result={}", JSON.toJSONString(result));
			supplierName = result == null ? supplierName : result.getSupplierName();
		} catch (Exception e) {
			logger.error("通过供应商id查询供应商信息接口异常,e={}",e);
		}
		return supplierName;
	}


	/**
	 * 根据分类id获取商品数量
	 */
	@Override
	public Integer getProductCountByClassify(Long classifyId) {
		PhProduct record = new PhProduct();
		record.setProductClassifyId(classifyId);
		return phProductMapper.selectCount(record);
	}
	

}
